import React from 'react'
import {Form, Modal, Input, Select, Tree, Button, Upload, Icon} from 'antd';
import API from "../../axios/api";
import {ProductType} from "../../utils/system-data";
import {beforeUpload} from '../../utils/utils'
import config from '../../config';
const BaseUrl = config.apiURL

const { TextArea } = Input;


class ProductForm extends React.Component {
    constructor(props){
        super(props)
        this.state = {
            expandedKeys: [],
            autoExpandParent: true,
            checkedKeys: [],
            selectedKeys: [],
            treeData: [],
            editorContent: '',
            imgList: [],
            // fileList: [],
            clear: false,
            previewVisible: false,
            previewImage: '',
            fileList: [
                {
                    uid: '-1',
                    name: 'xxx.png',
                    status: 'done',
                    url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
                },
            ],
            Id: "",
            shareImage: []
        };
        this.handleSubmit = this.handleSubmit.bind(this)
        this.onBlurEditor = this.onBlurEditor.bind(this)
        this.onImgUploadChange = this.onImgUploadChange.bind(this)
    }

    onExpand = expandedKeys => {
        console.log('onExpand', expandedKeys);
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        });
    };

    onCheck = checkedKeys => {
        console.log('onCheck', checkedKeys);
        this.setState({ checkedKeys });
    };

    onSelect = (selectedKeys, info) => {
        console.log('onSelect', info);
        this.setState({ selectedKeys });
    };
    componentDidMount() {
        const good  = this.props.good
        if(this.props.good){
            this.setState({
                Id: this.props.good.Id,
                shareImage: (good && good.ShareImage) || []
            })
        }
    }

    handleSubmit = (e) => {
        e && e.preventDefault()
        this.props.form.validateFields((err, values) => {
            if (!err) {
                // values.Id = this.state.Id

                if(values.Catty == ''){
                    values.Catty = 0
                }
                values.shareImage = ''
                if(values.shareImageUpload && values.shareImageUpload.length > 0){
                    values.shareImage = values.shareImageUpload[0].response.Data
                }
                values.MainGoodsImageList = []
                if(values.upload && values.upload.length > 0){
                    let _list = [];
                    values.upload.map(item => {
                        _list.push({
                            ImageUrl: item.response.Data
                        })
                    })
                    values.MainGoodsImageList = _list
                }
                const { onOk } = this.props
                onOk && onOk(values)
                this.props.form.resetFields()
                this.setState({imgList:[]})
            }
        })
    }

    handlerClose = (fn) => {
        this.props.form.resetFields()
        this.setState({ checkedKeys : []})
        fn()
    }

    getRolePermByRoleId =  async (Id) => {
        const parms = {
            Id
        }
        await API.getRolePermissionByRoleId(parms).then((res) => {
            if(res.Code === 200) {
                let checkedKeys = res.Data
                this.setState({
                    checkedKeys
                });
            }
        })
    }

    onBlurEditor(value){
        this.setState({
            editorContent: value
        })
    }

    onImgUploadChange(value){
        this.setState({
            imgList : value
        })
    }

    componentWillReceiveProps(nextProps, nextContext) {
        this.setState({
            imgList: []
        })
    }

    shareNormFile = e => {
        console.log('Upload event:', e);
        if (Array.isArray(e)) {
            return e;
        }
        this.setState({
            shareImage: e.fileList
        })
        return e && e.fileList;
    }

    normFile = e => {
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const {
            modalKey,
            visible,
            title,
            fields,
            onCancel,
            onOk,
            okText,
            width,
            good
        } = this.props
        let shareImageFile = (good && good.ShareImage) || []
        let defaultFileList = (good && good.GoodsImageList) || []
        let UploadImageUrl = BaseUrl + '/api/aboutapi/UploadImage'
        let UploadVideoUrl = BaseUrl + '/api/aboutapi/UploadVideo'
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 4 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
        }

        return (
            <Modal
                wrapClassName="form"
                key={modalKey}
                visible={visible}
                title={title}
                onCancel={onCancel}
                footer={null}
                width={width}
            >
                <Form onSubmit={this.handleSubmit}  {...formItemLayout} className="login-form">
                    <Form.Item label="商品名称">
                        {getFieldDecorator('Name', {
                            initialValue: good && good.Name,
                            rules: [{ required: true, message: '商品名称必填！' }],
                        })(<Input/>)}
                    </Form.Item>
                    {getFieldDecorator('Id',{
                        initialValue: good && good.Id,
                    })(<Input type="hidden"/>)}
                    <Form.Item label="商品规格">
                        {getFieldDecorator('Rule', {
                            initialValue: good && good.Rule,
                            rules: [{ required: true, message: '商品规格必填！' }],
                        })(<Input/>)}
                    </Form.Item>
                   {/** <Form.Item label="商品库存">
                        {getFieldDecorator('Stock', {
                            initialValue: good && good.Stock
                        })(<Input/>)}
                    </Form.Item> */}
                    <Form.Item label="重量(斤)">
                        {getFieldDecorator('Catty', {
                            initialValue: good && good.Catty,
                        })(<Input/>)}
                    </Form.Item>
                    <Form.Item label="媒体价">
                        {getFieldDecorator('MediaPrcie', {
                            initialValue: good && good.MediaPrcie,
                            rules: [{ required: true, message: '媒体价必填！' }],
                        })(<Input/>)}
                    </Form.Item>
                    <Form.Item label="会员价">
                        {getFieldDecorator('MemberPrice', {
                            initialValue: good && good.MemberPrice,
                            rules: [{ required: true, message: '会员价必填！' }],
                        })(<Input/>)}
                    </Form.Item>
                    <Form.Item label="商品类型">
                        {getFieldDecorator('GoodsType', {
                            initialValue: good && good.GoodsType,
                            rules: [{ required: true, message: '商品类型必选' }],
                        })(
                            <Select disabled={(good) ? true : false}>
                                {
                                    ProductType && ProductType.map(item => {
                                        return (<option key={item.value} value={item.value}>{item.mean}</option>
                                        )
                                    })
                                }
                            </Select>,
                        )}
                    </Form.Item>
                    <Form.Item label="详情">
                        {getFieldDecorator('Content',{
                            initialValue: good && good.Content,

                        })(
                            <TextArea rows="4" />
                        )}
                    </Form.Item>

                    <Form.Item label="转发封面" >
                        {getFieldDecorator('shareImageUpload', {
                            valuePropName: 'fileList',
                            getValueFromEvent: this.shareNormFile,
                            initialValue: shareImageFile
                        })(
                            <Upload name="logo1"
                                    action = {UploadImageUrl}
                                    listType="picture"
                                    beforeUpload={beforeUpload}
                            >
                                {this.state.shareImage && this.state.shareImage.length >0 ?  <br /> :
                                    <Button><Icon type="upload" />Click to upload</Button>
                                }

                            </Upload>,
                        )}
                        <span>转发封面请上传 大小小于100k  图片为正方形</span>
                    </Form.Item>

                    <Form.Item label="商品图片" >
                        {getFieldDecorator('upload', {
                            valuePropName: 'fileList',
                            getValueFromEvent: this.normFile,
                            initialValue: defaultFileList
                        })(
                            <Upload name="logo"
                                    action = {UploadImageUrl}
                                    listType="picture"
                                    beforeUpload={beforeUpload}
                            >
                                <Button>
                                    <Icon type="upload" /> Click to upload
                                </Button>
                            </Upload>,
                        )}
                    </Form.Item>

                    <div className="buttons">
                        {this.props.showCancel && <Button onClick={this.onCancel} >取消</Button>}
                        {!this.props.noBtn && <Button type="primary" htmlType="submit">{this.props.okText || '确定'}</Button>}
                    </div>
                </Form>
            </Modal>
        );
    }
}
let ProductModalForm = Form.create()(ProductForm)

export default ProductModalForm

